package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.feigns.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.Article.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.mess.app.AggBehaviorDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

//@Service
@Transactional
@Slf4j
//public class HotArticleServiceImpl1 implements HotArticleService {
public class HotArticleServiceImpl1  {

    @Autowired
    ApArticleMapper apArticleMapper;

    @Autowired
    AdminFeign adminFeign;

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 计算热文章
     */
   // @Override
    public void computeHotArticle() {
        //1 查询前5天的 （已上架、未删除） 文章数据
        //拿到五天之前的数据 用数据大于那个最小时间进行查询(String类型)
        String date = LocalDateTime.now().minusDays(5)
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00"));
        List<ApArticle> articleList = apArticleMapper.selectArticleByDate(date);
        //2. 到数据库根据 计算热文章的参数进行计算
        List<HotArticleVo> hotArticleVoList = computeArticleScore(articleList);
        //3 为每一个频道缓存热点较高的30条文章
        cacheTagToRedis(hotArticleVoList);
    }

    /**
     * 为每一个频道缓存热点较高的30条文章
     *
     * @param hotArticleVoList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        //拿到全部频道
        ResponseResult<List<AdChannel>> responseResult = adminFeign.selectChannels();
        if (responseResult.getCode() == 0) {
            List<AdChannel> list = responseResult.getData();
            //2 遍历频道列表，筛选当前频道下的文章
            for (AdChannel adChannel : list) {
                //3 给每个频道下的文章进行缓存
                List<HotArticleVo> hotArticleVos = hotArticleVoList.stream()
                        // 当前频道下的文章列表
                        .filter(hotArticle -> hotArticle.getChannelId().equals(adChannel.getId()))
                        .collect(Collectors.toList());
                sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + adChannel.getId());
            }
        }
        sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG );
    }

    /**
     * 缓存热点文章
     * @param hotArticleVos
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String cacheKey) {
        // 对文章进行排序
        hotArticleVos = hotArticleVos.stream()
                //排序
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        //存入redis中
        redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleVos));
    }


    /**
     * 拿到数据库的计算热文章的参数进行计算
     *
     * @param articleList
     * @return
     */
    private List<HotArticleVo> computeArticleScore(List<ApArticle> articleList) {
        int score = 0;
        ArrayList<HotArticleVo> list = new ArrayList<>();
        for (ApArticle apArticle : articleList) {
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle, hotArticleVo);
            if (apArticle.getViews() != null) {
                score += apArticle.getViews() * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
            }
            // 点赞 3
            if (apArticle.getLikes() != null) {
                score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
            }
            // 评论 5
            if (apArticle.getComment() != null) {
                score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
            }
            // 收藏 8
            if (apArticle.getCollection() != null) {
                score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
            }
            hotArticleVo.setScore(score);
            list.add(hotArticleVo);
        }
        return list;
    }

    //@Override
    public void updateApArticle(AggBehaviorDTO aggBehavior) {

    }
}
